package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.Category;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.CategoryMapper;
import com.leyou.item.service.CategoryBrandService;
import com.leyou.item.service.CategoryService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Resource
    private CategoryBrandService categoryBrandService;

    //根据品牌id，查询商品分类的集合
    @Override
    public List<CategoryDTO> queryCategoryByBrandId(Long brandId) {
        // 1.根据品牌id，查询中间表，得到中间表对象集合
        // 查询中间表 SELECT * FROM tb_category_brand WHERE brand_id = 18374
        List<CategoryBrand> categoryBrandList = categoryBrandService.query().eq("brand_id", brandId).list();
        if (CollectionUtils.isEmpty(categoryBrandList)) {
            return Collections.emptyList();
        }
        // 2.获取分类id集合
        List<Long> categoryIdList = new ArrayList<>(categoryBrandList.size());
        for (CategoryBrand categoryBrand : categoryBrandList) {
            categoryIdList.add(categoryBrand.getCategoryId());
        }
        //使用stream流更加优雅
//        List<Long> categoryIdList = categoryBrandList.stream()
//                .map(CategoryBrand::getCategoryId).collect(Collectors.toList());
        // 3.根据分类id集合，查询分类对象集合
        List<Category> categories = listByIds(categoryIdList);
        // 4.转换DTO
        return CategoryDTO.convertEntityList(categories);
    }

}
